package com.mercury.logs.aop.aspect;

import com.mercury.logs.aop.annoaction.MercuryLog;
import com.mercury.logs.entity.MercuryLogEntity;
import com.mercury.logs.enums.MercuryLogTypeEnum;
import com.mercury.logs.holder.SpringContextHolder;
import com.mercury.logs.listener.MercuryLogEvent;
import com.mercury.logs.manager.MercuryLogUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

/**
 * 操作日志使用spring event异步入库
 *
 * @author mercury
 */
@Aspect
@Slf4j
public class MercuryLogAspect {

    @Around("@annotation(mercuryLog)")
    @SneakyThrows
    public Object around(ProceedingJoinPoint point, MercuryLog mercuryLog) {
        String strClassName = point.getTarget().getClass().getName();
        String strMethodName = point.getSignature().getName();
        log.debug("[类名]:{},[方法]:{}", strClassName, strMethodName);

        MercuryLogEntity logVo = MercuryLogUtils.getSysLog();
        logVo.setTitle(mercuryLog.value());

        // 发送异步日志事件
        Long startTime = System.currentTimeMillis();
        Object obj;

        try {
            obj = point.proceed();
        } catch (Exception e) {
            logVo.setType(MercuryLogTypeEnum.ERROR.getType());
            logVo.setException(e.getMessage());
            throw e;
        } finally {
            Long endTime = System.currentTimeMillis();
            logVo.setTime(endTime - startTime);
            //spring 发送事件 !!!!!
            SpringContextHolder.publishEvent(new MercuryLogEvent(logVo));
        }

        return obj;
    }

}
